const axios = require("axios");
var express = require("express");
// var request = require("request")
let router = express.Router();
var moment = require("moment");
var COS = require("cos-nodejs-sdk-v5");
const { RSA_NO_PADDING } = require("constants");
const { ohana } = require("ohana-node-orm");
const constants = require("../utils/constants");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

var cos = new COS({
    SecretId: "AKIDnSu88wiaSEoAKJ6f070e3E9rKZhhU1Vp",
    SecretKey: "A6nFdzCDzYtzqa8RYS8YjpmYBbnkSvBF",
});
router.get("/", function (req, res, next) {
    const { cat, id } = req.query;
    if (!cat || !id) {
        res.status(400).send({ message: "没有cat和id参数" });
        return;
    }
    getThatQR({ path: "pages/home/index?cat=" + cat + "&id=" + id })
        .then((result) => {
            fileName = cat + id + ".jpeg";
            const fileContents = Buffer.from(result.data, "base64");
            cos.putObject(
                {
                    Bucket: "jiangdutest-1307977142" /* 必须 */,
                    Region: "ap-shanghai" /* 必须 */,
                    Key: fileName /* 必须 */,
                    Body: fileContents,
                },
                function (err, data) {
                    if (data.statusCode == 200) {
                        log.info(data.Location);
                        updateQRCode(cat, id, data.Location)
                            .then((result) => {
                                if (result > 0) {
                                    res.send({ message: "cool", code: 200 });
                                } else {
                                    res.status(400).send({ message: "更新错误" });
                                }
                            })
                            .catch((err) => {
                                log.error(err);
                                res.status(500).send(err);
                            });
                    } else {
                        res.status(400).send(data);
                    }
                }
            );
        })
        .catch((err) => {
            log.error(err);
            res.status(500).send(err);
        });
});
async function getThatQR(payload) {
    var wxCredential = {
        appid: "wxe5886d1b9a1b5225",
        appsecret: "98e7312ebb897325bbbe4b76c1ee4f13",
    };
    var urlString =
        "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" +
        wxCredential.appid +
        "&secret=" +
        wxCredential.appsecret;
    var result = await axios.get(urlString);
    const { data } = result;
    var postString =
        "https://api.weixin.qq.com/wxa/getwxacode?access_token=" +
        data.access_token;
    var QRresult = await axios.post(postString, payload, {
        responseType: "arraybuffer",
    });
    return QRresult;
}

async function updateQRCode(cat, id, location) {
    let sqlConn = null;
    let targetId = {};
    switch (cat) {
        case "policys":
            sqlConn = new ohana(constants.POLICYTABLE);
            targetId = { POLICY_ID: id };
            break;
        case "talents":
            sqlConn = new ohana(constants.TALENTTABLE);
            targetId = { TALENT_ID: id };
            break;
        case "fins":
            sqlConn = new ohana(constants.FINTABLE);
            targetId = { FIN_ID: id };
            break;
        case "assets":
            sqlConn = new ohana(constants.ASSETTABLE);
            targetId = { ASSET_ID: id };
            break;
        case "techs":
            sqlConn = new ohana(constants.TECHTABLE);
            targetId = { TECH_ID: id };
            break;
        default:
            break;
    }
    var result = await sqlConn.update(targetId, {
        QRCODE: "https://" + location,
        UPDATED_AT: moment(new Date()).format("YYYY-MM-DD HH:mm:ss"),
    });
    return result;
}
module.exports = router;
